<template>
    <div class="app-container">
        <a-button type="primary" @click="(openModal as any)">新增分类</a-button>
        <div class="table-head">
            <div>分类名称</div>
            <div>排序</div>
            <div>分类类型</div>
            <div>操作</div>
        </div>
        <a-empty v-if="!data.length"></a-empty>
        <a-scrollbar style="max-height:calc(100vh - 300px);overflow-y: scroll;">
            <Tree :data="data" :type="type">
                <template #btn="{ row }">
                    <a-button type="text" @click="openModal(row)" v-if="!(row.level > 2)">添加</a-button>
                    <a-button type="text" @click="openModal(row, true)">编辑</a-button>
                    <a-button type="text" @click="openDel(row)">删除</a-button>
                </template>
                <template #input="{ row }">
                    <a-input-number style="width: 70px;" v-model="row.sort" :min="1" @blur="changeSort(row)"
                        @keyup.enter="changeSort(row)"></a-input-number>
                </template>
            </Tree>
        </a-scrollbar>
        <a-modal v-model:visible="visible" :width="600" hide-title @close="close" :on-before-ok="confirm"
            unmountOnClose>
            <CustomTitle :title="modelTitle" style="margin-bottom: 20px;" />
            <a-scrollbar style="max-height:80vh;overflow: auto;">
                <a-form :model="form" :rules="rules" ref="formRef">
                    <a-form-item label="上一级分类" v-if="!child">
                        <div>{{ addRow.name }}</div>
                    </a-form-item>
                    <a-form-item label="分类名称" field="billCategoryName">
                        <a-input v-model="form.billCategoryName" placeholder="请输入分类名称"></a-input>
                    </a-form-item>
                    <a-form-item label="提醒语" field="promptMsg">
                        <a-textarea placeholder="请输入" v-model="form.promptMsg"></a-textarea>
                    </a-form-item>
                    <a-form-item label="排序" field="sort">
                        <a-input-number style="width: 150px;" v-model="form.sort" mode="button" :min="1" />
                    </a-form-item>
                </a-form>
            </a-scrollbar>
        </a-modal>
        <!--  删除角色/账户弹窗 -->
        <a-modal v-model:visible="delVisible" @ok="del" okText="确定" cancelText="取消" width="400px" :mask-closable="false"
            unmountOnClose :closable="false">
            <div class="modal-message">
                <div class="del-name">{{ delDetail.billCategoryName }}</div>
                <div class="del-tip">确认删除该节点及子节点的内容？</div>
            </div> 
        </a-modal>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from "vue";
import Tree from "./components/Tree.vue";
import CustomTitle from "@/components/CustomTitle/index.vue";
import { getOtherCategoryTree, addLoanCategory, editLoanCategory, deleteLoanCategory, getConfigSubjectList, getOaFormList, getLoanCategoryDetail } from "@/apis/system";
import type { LoanParams } from "@/apis/system/type";
import { Message } from '@arco-design/web-vue';

const formKey = ref("");
const loading = ref(false);
const data = ref([]);
const visible = ref(false);
const type: { [key: number]: string } = {
    1: '资产',
    2: '负债',
    3: '权益',
    4: '损益-收入',
    5: '损益-费用'
}
const delVisible = ref(false);
const formRef = ref(null);
const addRow = ref({
    name: '',
    type: 1,
    code: ''
});
const defaultItem: LoanParams = {
    billCategoryName: '',
    formId: '',
    formName: '',
    type: 1,
    promptMsg: '',
    parentBillCategoryId: '',
    sort: 1,
    billSubjectStageReq: {
        approves: [],
        accountPayment: [],
        debitSlipPayment: []
    }
}
/**
 * 重置
 */
const reset = () => {
    (formRef as any).value.resetFields();
    form.value = { ...JSON.parse(JSON.stringify(defaultItem)) };
    console.log(form.value)
}
/**
 * 删除详情
 */
const delDetail = ref<LoanParams>({
    ...JSON.parse(JSON.stringify(defaultItem))
})
/**
 * 表单or默认值
 */
const form = ref<LoanParams>({
    ...JSON.parse(JSON.stringify(defaultItem))
});
/**
 * 是否新建
 */
const isNew = ref(true);
/**
 * 打开删除弹窗
 */
const openDel = (row: LoanParams) => {
    delDetail.value = { ...row };
    delVisible.value = true;
}
/**
 * 确认删除
 */
const del = async () => {
    await deleteLoanCategory(delDetail.value.billCategoryId as string);
    init();
    Message.success('删除成功');
}
/**
 * 初始化列表
 */
const init = async () => {
    const res = await getOtherCategoryTree();
    data.value = res.data;
}
/**
 * 关闭弹窗后的回调
 */
const close = () => {
    visible.value = false;
    reset();
}
/**
 * 校验弹窗表单
 */
const verify = async () => {
    let arr = [];
    arr.push(new Promise(resolve => {
        (formRef as any).value.validate((errors: any) => {
            resolve(errors == void 0);
        })
    }));
    const result = await Promise.all(arr);
    return result.every(v => v);
}
const confirm = async () => {
    const close = (res: { code: number }) => {
        if (res.code == 200) {
            init();
        }
        return res.code == 200;
    }
    if (await verify()) {
        if (isNew.value) {
            const res = await addLoanCategory({...form.value,type:3});
            return close(res)
        } else {
            const res = await editLoanCategory({...form.value,type:3});
            return close(res)
        }
    }
    return false;
}
/**
 * 改变排序
 */
const changeSort = async (row: LoanParams) => {
    const res = await getLoanCategoryDetail(row.billCategoryId as string);
    form.value = { ...res.data, sort: row.sort };
    await editLoanCategory(form.value);
    Message.success('修改成功');
    init();
}
const child = ref()
const modelTitle = ref('新增分类');
const isChild = async (row: LoanParams, isEdit = false) => {
    if (!row.billCategoryId) {
        modelTitle.value = '新增分类';
        child.value = true;
    } else {
        if (isEdit) {
            const res = await getLoanCategoryDetail(row.billCategoryId);
            form.value = res.data;
            if (row.parentBillCategoryId) {
                modelTitle.value = '编辑子分类';
                child.value = false;
            } else {
                modelTitle.value = '编辑分类';
                child.value = true;
            }
        } else {
            modelTitle.value = '新增子分类';
            child.value = false;
        }
    }
};
const getParent = (treeData: any[], parentSubjectId: string) => {
    treeData.forEach(item => {
        if (item.subjectId == parentSubjectId) {
            addRow.value = {
                name: item.subjectName,
                type: item.subjectType,
                code: item.subjectCode
            }
        } else if (item.children && item.children.length) {
            getParent(item.children, parentSubjectId)
        }
    })
}
const openModal = (row: LoanParams, isEdit = false) => {
    isChild(row, isEdit);
    if (!isEdit) {
        isNew.value = true;
        if (row.billCategoryId) {
            addRow.value.name = row.billCategoryName;
            form.value.parentBillCategoryId = row.billCategoryId;
        }
    } else {
        isNew.value = false;
        form.value = { ...row };
    }
    visible.value = true;
}
const rules = {
    billCategoryName: [
        { required: true, message: '请输入科目名称', trigger: 'blur' },
        { maxLength: 32, message: '科目名称不能超过32个字符', trigger: 'blur' }
    ],
    formId: [
        { required: true, message: '请选择', trigger: 'change' }
    ],
    type: [
        { required: true, message: '请选择账户类别', trigger: 'blur' },
    ],
    sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
    promptMsg: [{ maxLength: 30, message: '提示语不能超过30个字符' }]
}
const subjectList = ref<any[]>([])
/**
 * 过滤出子节点
 */
const getChild = (treeData: any[]) => {
    treeData.forEach(v => {
        if (v.children && v.children.length) {
            getChild(v.children)
        } else {
            subjectList.value.push(v)
        }
    })
}
const getSubjectTree = async () => {
    const res = await getConfigSubjectList();
    subjectList.value=res.data;
};
const oaList = ref<any[]>([])
const getOA = async () => {
    const res = await getOaFormList({ groupId: 1 });
    oaList.value = res.data;
}
onMounted(() => {
    init();
    getSubjectTree();
    getOA()
})
</script>

<style lang="scss" scoped>
$border: 1px solid #DCDFE6;

.table-head {
    height: 50px;
    display: grid;
    grid-template-columns:repeat(4, 1fr);
    background: #F2F6FC;
    line-height: 50px;
    text-align: center;
    margin: 20px 0 10px;

    >div:first-child {
        text-align: left;
        padding-left: 20px;
    }
}

.arco-radio-group {
    line-height: 36px;
}

.modal-message {
    text-align: center;

    .del-name {
        width: 80%;
        margin: 12px auto;
        height: 60px;
        line-height: 60px;
        border: $border;
    }
}

.subject-box {
    width: 100%;
    display: grid;
    grid-template-columns: 1fr;
    row-gap: 10px;

    >div {
        border: $border;

        >div:nth-child(1) {
            height: 32px;
            background: #F5F7FA;
            line-height: 32px;
            padding-left: 16px;
            border-bottom: $border;
        }

        .add {
            color: #007DFF;
            line-height: 40px;
            user-select: none;
            width: 120px;
            display: flex;
            gap: 8px;
            align-items: center;
        }

        >div:last-child {
            .list {
                min-height: 46px;
                display: flex;
                gap: 10px;
                padding: 10px 16px 0;
                box-sizing: border-box;
                align-items: center;
                max-width:441px;
                :deep(.arco-form-item-label-col) {
                    display: none;
                }

                :deep(.arco-form-item-wrapper-col) {
                    flex: 1;
                }
                :deep(.arco-form-item){
                    width:46%;
                }
                :deep(.arco-row-justify-start) {
                    margin-bottom: 0;
                }

                img {
                    width: 16px;
                    height: 16px;
                }

                ::v-deep(.arco-select_wrapper) {
                    height: 32px;
                }
            }

            >div {
                height: 40px;
                padding: 0 16px;
            }

            .prefix {
                border-right: $border;
                height: 100%;
                line-height: 32px;
                padding-right: 10px;
            }
        }
    }
}

.search-box {
    :deep(.arco-input-wrapper) {
        border: none;
        border-radius: 0;
    }
}
</style>
